package cn.hhchat.wp.controller;

import cn.hhchat.wp.config.SystemProperties;
import cn.hhchat.wp.dto.form.CreateGroupForm;
import cn.hhchat.wp.dto.group.SimpleGroupInfo;
import cn.hhchat.wp.dto.group.SimpleGroupPostInfo;
import cn.hhchat.wp.dto.group.SimpleJoinRelation;
import cn.hhchat.wp.dto.msg.RMsg;
import cn.hhchat.wp.dto.msg.RMsgFactory;
import cn.hhchat.wp.dto.msg.RMsgModel;
import cn.hhchat.wp.dto.table.EleTable;
import cn.hhchat.wp.dto.user.SimpleUser;
import cn.hhchat.wp.entity.JoinRelationEntity;
import cn.hhchat.wp.entity.PostEntity;
import cn.hhchat.wp.entity.GroupEntity;
import cn.hhchat.wp.entity.UserEntity;
import cn.hhchat.wp.exception.BadAuthenticationException;
import cn.hhchat.wp.exception.BadQueryException;
import cn.hhchat.wp.exception.UnAuthenticationException;
import cn.hhchat.wp.service.GroupService;
import cn.hhchat.wp.service.PostService;
import cn.hhchat.wp.service.UserService;
import cn.hhchat.wp.util.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created this one by HMH on 2017/10/22.
 */
@Slf4j
@RestController
@RequestMapping("/group")
public class GroupController {

    @GetMapping("/getGroupsInfoInTable")
    public RMsg getGroupsInfoInTable() {
        UserEntity user = SessionUtil.getUser();
        if (user == null) {
            throw new BadAuthenticationException("未登录");
        }
        //查询我的
        List<GroupEntity> myGroups = groupService.getAllUnFinishedByActiveUser(user);
        //查询所有
        List<GroupEntity> allGroups = groupService.getAllUnFinished();
        List<SimpleGroupPostInfo> myGroupsTableInfo = myGroups.stream().map(g->groupService.toSimpleGroupPostInfoOfThisWeek(g,user)).collect(Collectors.toList());
        List<SimpleGroupPostInfo> allGroupsTableInfo = allGroups.stream().map(g->groupService.toSimpleGroupPostInfoOfThisWeek(g,user)).collect(Collectors.toList());
        EleTable myGroupsTable = new EleTable(myGroupsTableInfo);
        EleTable allGroupsTable = new EleTable(allGroupsTableInfo);

//        返回
        return RMsgFactory.ok(new RMsgModel().add("myGroups", myGroupsTable).add("allGroups", allGroupsTable).data());
    }

    @GetMapping
    public RMsg getGroupInfo(@RequestParam Long id){
        GroupEntity group = groupService.getById(id);
        return RMsgFactory.ok(group.toSimpleGroup());
    }

    @GetMapping("/getAllInTable")
    public RMsg getAllInTable() {
        List<GroupEntity> list = groupService.getAll();
        List<SimpleGroupInfo> result = list.stream().map(groupService::toSimpleGroupInfo).collect(Collectors.toList());
        EleTable groupTable = new EleTable(result);
        return RMsgFactory.ok(groupTable);
    }

    @PostMapping("/finish")
    public RMsg finishGroup(@RequestParam Long id) {
        GroupEntity groupEntity = groupService.getById(id);
        groupService.finish(groupEntity);
        return RMsgFactory.ok();
    }

    @PostMapping("/restart")
    public RMsg reStartGroup(int id) {
        GroupEntity groupEntity = groupService.getById(id);
        groupService.reStart(groupEntity);
        return RMsgFactory.ok();
    }

    @PutMapping
    public RMsg create(@Valid @RequestBody CreateGroupForm form) {
        UserEntity user = SessionUtil.getUser();
        if (null == user) {
            throw new UnAuthenticationException();
        }
        return RMsgFactory.ok(groupService.createGroup(form, user).toSimpleGroup());
    }

    @GetMapping("/getMembersInTable")
    public RMsg getMembersInTable(@RequestParam long id){
        GroupEntity group = groupService.getById(id);
        if (null == group) {
            throw new BadQueryException("没有找到id为" + id + "的项目组");
        }
        List<SimpleJoinRelation> joinList = groupService.getMembers(group).stream().map(JoinRelationEntity::toSimpleJoinRelation).collect(Collectors.toList());
        EleTable joinTable = new EleTable(joinList);
        return RMsgFactory.ok(joinTable);
    }

    @PostMapping("/addMember")
    public RMsg addMember(@RequestParam long userId, @RequestParam long groupId) {
        GroupEntity group = groupService.getById(groupId);
        if (null == group) {
            throw new BadQueryException("项目组错误");
        }
        UserEntity userEntity = userService.getById(userId);
        if (null == userEntity) {
            throw new BadQueryException("用户错误");
        }
        JoinRelationEntity joinRelation = groupService.join(group, userEntity, true);
        return RMsgFactory.ok(joinRelation.toSimpleJoinRelation());
    }

    @PostMapping("/setAsAdmin")
    public RMsg setAdmin(@RequestParam long userId, @RequestParam long groupId, @RequestParam boolean isAdmin) {
        GroupEntity group = groupService.getById(groupId);
        if (null == group) {
            throw new BadQueryException("项目组错误");
        }
        UserEntity user = userService.getById(userId);
        if (null == user) {
            throw new BadQueryException("用户错误");
        }
        groupService.setAdmin(group, user, isAdmin);
        return RMsgFactory.ok();
    }

    @PostMapping("/removeMember")
    public RMsg removeMember(@RequestParam long userId, @RequestParam long groupId) {
        GroupEntity group = groupService.getById(groupId);
        if (null == group) {
            throw new BadQueryException("项目组错误");
        }
        UserEntity userEntity = userService.getById(userId);
        if (null == userEntity) {
            throw new BadQueryException("用户错误");
        }
        groupService.removeMember(group, userEntity);
        return RMsgFactory.ok();
    }

    @PostMapping("/setSubscribe")
    public RMsg setSubscribe(@RequestParam long userId, @RequestParam long groupId, @RequestParam boolean isSubscribe){
        GroupEntity group = groupService.getById(groupId);
        if (null == group) {
            throw new BadQueryException("项目组错误");
        }
        UserEntity user = userService.getById(userId);
        if (null == user) {
            throw new BadQueryException("用户错误");
        }
        groupService.setSubscribe(group, user, isSubscribe);
        return RMsgFactory.ok();
    }

    @GetMapping("/getMyGroupList")
    public RMsg getMyGroupList() {
        UserEntity user = SessionUtil.getUser();
        List<GroupEntity> groups = groupService.getAllUnFinishedByActiveUser(user);
        return RMsgFactory.ok(groups.stream().map(GroupEntity::toSimpleGroup).collect(Collectors.toList()));
    }

    @GetMapping("/getAllPostersOfGroupInWeek")
    public RMsg getAllPostersOfGroupInWeek(long groupId, int year, int week) {
        GroupEntity group = groupService.getById(groupId);
        List<PostEntity> posts = postService.getPostOfGroupInWeek(group, year, week);
        List<SimpleUser> posters = posts.stream().map(PostEntity::getPoster).distinct().map(UserEntity::toSimpleUser).collect(Collectors.toList());
        return RMsgFactory.ok(posters);
    }

    @GetMapping("/getAllMembers")
    public RMsg getAllMembers(long id){
        GroupEntity group = groupService.getById(id);
        List<JoinRelationEntity> joiners = groupService.getMembers(group);
        List<SimpleUser> users = joiners.stream().map(j -> j.getUser().toSimpleUser()).collect(Collectors.toList());
        return RMsgFactory.ok(users);
    }

    @PostMapping("/setNeedSubmit")
    public RMsg setNeedSubmit(long groupId, long userId, boolean needSubmit){
        GroupEntity group = groupService.getById(groupId);
        UserEntity user = userService.getById(userId);
        groupService.setNeedSubmit(group, user, needSubmit);
        return RMsgFactory.ok();
    }

    @PostMapping("/setPostTemplate")
    public RMsg setPostTemplate(long id,String template){
        GroupEntity group = groupService.getById(id);
        groupService.setPostTemplate(group, template);
        return RMsgFactory.ok();
    }

    @Autowired
    private UserService userService;

    @Autowired
    private GroupService groupService;

    @Autowired
    private SystemProperties sysConfig;

    @Autowired
    private PostService postService;


}
